# server.py
import re
from mcp.server.fastmcp import FastMCP
import requests
from services.cube import *
import time,datetime
from utils.logger import logger
from services.bailian import BaiLianServices
# Create an MCP server
mcp = FastMCP("Demo",port=8001)

@mcp.tool()
def get_now_time() -> datetime.datetime:
    """
        获取当前时间
    """
    logger.info("调用工具:获取当前时间")
    return datetime.datetime.now()

@mcp.tool(description="""使用向量搜索技术搜索指标、维度或筛选条件信息，支持单次搜索或批量搜索，参数格式如下{
    list(dict(
            "type":str.describe("搜索类型,支持'metric','demensoin','filter'"),
            "keyword":str.describe("检索的内容")
        ))
}""")
# :list[dict:{"type":str,"keyword":str}]
def vector_search(params):
    """
        向量搜索
    """
    logger.info("调用工具:向量搜索")
    logger.info(f"参数:{params}")
    # 遍历参数列表,异步调用百炼接口
    result = []
    for param in params:
        # 调用百炼接口
        response = BaiLianServices.search_knowledge_base(param["type"],param["keyword"])
        # 解析百炼返回结果
        response = json.loads(response)
        result.append(response)
    logger.info(f"调用工具:向量搜索成功")
    return json.dumps(result,ensure_ascii=False)

@mcp.tool(description="""获取订单流转的整体指标数据，参数格式如下{
    "conditions":dict{str.describe("条件项ID"):list(int.describe("条件值ID"))")},
    "timeRange":str.describe("查询时间范围,格式如'2025/03/26 00:00:00 - 2025/03/26 23:59:59'"),
    "comparedTimeRange":str.describe("需要对比的时间范围,可选,格式为'2025/03/26 00:00:00 - 2025/03/26 23:59:59'")
    }""")
def get_ordercirc_data(conditions:dict,timeRange:str,comparedTimeRange:str=None) -> list:
    """_summary_
        获取订单流转的整体指标数据
    Args:
        conditions (dict): 查询条件,格式为
            {
                "条件项id":[条件值id,条件值id],
            }
            如  {
                "10032": "500100",
                "10043": "1013,1016"
            }
        timeRange (str): 查询时间范围,格式如
            "2025/03/26 00:00:00 - 2025/03/26 23:59:59"

        comparedTimeRange (_type_): 需要对比的时间范围,可选,格式为
            "2025/03/26 00:00:00 - 2025/03/26 23:59:59"

    Returns:
        str: _description_
    """

    measure_dict = {
        "下单": [
            [102001, "订单数","订单的数量，不含重复、测试、失败二级缘由为废弃的数据"],
            [102002, "新单数","工单类型为新工单的数量，不含废弃的新单"],
            [102102, "返修单数","工单类型为返修工单的数量，不含废弃、重复、测试的工单"]
        ],
        "派单": [
            [102246, "≥已派单","工单状态为≥已派单的工单数，含新单和返修单"],
            [102401, "派单率","派单率=派单量/订单量，含新单与返修单，不含废弃工单"],
            [800099, "派单准时率","派单准时率=派单准时单数/派单量，含新单和返修单，含废弃工单，不含用户类型为企业/个体户用户的工单数据"],
            [800108, "平均派单时长(分)","平均派单时长=派单时长/派单量，派单时长：派单时间和工单创建时间之差，不含夜间时间(21:30-7:30)；含新单和返修单，废弃工单"]
        ],
        "领单": [
            [800102, "领单准时单数","工单为准时领单标记的工单数，含新单和返修单，含废弃工单"],
            [800103, "领单准时率","领单准时率=领单准时单量/派单量，领单准时单量：工单为准时领单标记的工单数，含新单和返修单，含废弃工单"],
            [800109, "平均领单时长(分)","平均领单时长=领单时长/领单量，领单时长：领单时间和派单时间之差，不含夜间时间(22:00-6:00)，含新单和返修单，废弃工单"]
        ],
        "联系": [
            [102431, "及时有效联系率","及时有效联系率=及时有效联系单数/领单数；及时有效联系单数：工单标识为有效联系且未联系超时的工单，包含新单和返修单，含废弃工单"],
            [102442, "联系准时率","联系准时率=联系准时单量/领单数，包含新单和返修单，不含标记剔除工程师绩效，含废弃的工单数据"],
            # [104114, "有效联系单数","工单标记为有效联系的工单数，含新单和返修单，不含废弃工单"],
            # [104214, "及时有效联系单数","工单标识为有效联系且未联系超时的工单，包含新单和返修单，含废弃工单"],
            [800110, "平均联系时长(分)","平均联系时长=联系时长/领单量，联系时长：联系时间和领单时间之差，联系时间取首次联系时间，不含夜间时间(22:00-6:00)，含新单和返修单，废弃工单"]
        ],
        "上门": [
            [102403, "上门率","上门率=上门新单数/新单数，不含废弃工单"],
            # [102247, "上门新单数","工单状态≥已上门的新单数，不含废弃工单"],
            [102248, "≥已上门","工单状态≥已上门的工单数，含新单和返修单，不含废弃工单"],
            [102443, "已上门准时率","已上门准时率=上门准时单数/上门单数，上门准时单数：工单时效中上门未超时的单数；含新单和返修单，含废弃工单"],
            [800111, "平均上门时长(分)","平均上门时长=上门时长/上门单量，上门时长：上门时间和领单时间之差，不含夜间时间(22:00-6:00)，含新单和返修单，废弃工单"]
        ],
        "服务完成": [
            [800112, "平均服务时长(分)"],
            [102249, "≥已完成"],
            # [102250, "＜服务完成"],
            [102409, "完成率"],
            # [102708, "72h返修完成率"],
            [800113, "平均完成时长(分)"],
            # [2001731, "未完成进行中新单数"]
        ],
        "收单": [
            [102210, "已收单"]
        ],
        "算账": [
            [102211, "已算账"],
            [800216, "算账单数"]
        ],
        "退款": [
            # [2001459, "完成单退款率"],
            # [2001464, "完成单退款金额"],
            # [800236, "完成单退款单数"],
            [102105, "退款单数"],
            [102108, "退款率"],
            [103254, "退款金额"]
        ],
        "取消": [
            [800079, "平均取消时长(分)"],
            # [2001465, "取消单退款金额"],
            [2001460, "取消单退款单数"],
            [2001466, "取消单退款率"]
        ],
        "返修": [
            [102102, "返修单数"],
            [102103, "成功单返修率"],
            # [104118, "上门返修单数"],
            # [2000414, "进行中返修单数"],
            # [2001621, "返修单上门占比"]
        ]
    }
    measure_dict = {
        k:[_[:2] for _ in v] for k,v in measure_dict.items() for _ in v
    }
    # (conditions,dimension_row,measure_ids,time_range,compared_time_range)
    measure_ids = [item[0] for category in measure_dict.values() for item in category]
    logger.info(f"请求参数: conditions={conditions}, timeRange={timeRange}, comparedTimeRange={comparedTimeRange}")
    try:
        logger.info("开始获取Cube数据")
        logger.info(f"请求参数: conditions={conditions}, timeRange={timeRange}, comparedTimeRange={comparedTimeRange}")
        data = CubeServices.fetchBoradData(
            conditions=conditions,
            dimension_row=None,
            measure_ids=measure_ids,
            time_range=timeRange,
            compared_time_range=comparedTimeRange
        )
        logger.info("Cube数据获取完成")
    except Exception as e:
        logger.error(f"获取订单数据异常: {str(e)}", exc_info=True)
        return f"服务处理异常: {str(e)}"
    mea_data_string = CubeServices.format_cube_data(data)
    return_string = """以下是订单流转的指标信息"""
    return_string += json.dumps(measure_dict,ensure_ascii=False)
    return_string += """以下是订单流转指标数据"""
    return_string += mea_data_string
    return return_string

@mcp.tool(description="""查询自定义报表数据,参数格式如下:
{
    "metrics":list(int.describe("指标ID")),
    "filters":list(dict(
        int.describe("过滤条件ID"):list(int.describe("过滤条件值ID")))),
    "dimensions":list(int.describe("维度ID")).optional,
    "time_range":str.describe("时间范围,格式如'2025/03/26 00:00:00 - 2025/03/26 23:59:59'"),
    "compared_time_range":str.describe("对比时间范围,可选,格式为'2025/03/26 00:00:00 - 2025/03/26 23:59:59'").optional
}""")
def get_report_data(metrics,filters,dimensions,time_range,compared_time_range):
    """
    获取报表数据
    :param metrics: 指标列表
    :param filters: 过滤条件
    :param dimensions: 维度列表
    :param time_range: 时间范围
    :param compared_time_range: 对比时间范围
    :return: 报表数据
    """
    logger.info(f"调用工具:get_report_data")
    logger.info(f"参数:metrics={metrics}, filters={filters}, dimensions={dimensions}, time_range={time_range}, compared_time_range={compared_time_range}")
    try:
        logger.info("开始获取Cube数据")
        logger.info(f"请求参数: metrics={metrics}, filters={filters}, dimensions={dimensions}, time_range={time_range}, compared_time_range={compared_time_range}")
        data = CubeServices.fetchBoradData(
            conditions=filters,
            dimension_row=dimensions,
            measure_ids=metrics,
            time_range=time_range,
            compared_time_range=compared_time_range
        )
        logger.info("Cube数据获取完成")
    except Exception as e:
        logger.error(f"获取订单数据异常: {str(e)}", exc_info=True)
        return f"服务处理异常: {str(e)}"
    mea_data_string = CubeServices.format_cube_data(data)
    return mea_data_string

if __name__ == "__main__":
    # mcp.run(transport="stdio")
    mcp.run(transport="sse")


    # {  "server_name": {    "url": "http://0.0.0.0:8000/sse",    "headers": {}, "timeout": 60,    "sse_read_timeout": 300  }}